<!-- PO报表管理 -->
<template>
  <div class="equip-wrap-common">
    <px-form ref="queryRef" class="custom-form-ui equip-form" :model="queryParams" inline label-width="120px">
      <px-form-item label="PO号" prop="po">
        <px-select v-model="queryParams.poNumber" clearable placeholder="请选择PO号">
          <px-option v-for="item in poNoList" :key="item" :label="item" :value="item" />
        </px-select>
      </px-form-item>

      <px-form-item label="PO类型">
        <px-select v-model="queryParams.poType" placeholder="请选择PO类型" clearable filterable>
          <px-option v-for="item in poTypeList" :key="item.value" :label="item.label" :value="item.value" />
        </px-select>
      </px-form-item>

      <px-form-item label="PO提交人">
        <px-select v-model="queryParams.creator" placeholder="请选择PO提交人" clearable filterable>
          <px-option v-for="item in poCreatorList" :key="item" :label="item" :value="item" />
        </px-select>
      </px-form-item>
      <px-form-item label="PO创建时间">
        <px-date-picker
          v-model="queryParams.createTime"
          clearable
          type="daterange"
          range-separator="至"
          start-placeholder="请选择开始时间"
          end-placeholder="请选择结束时间"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </px-form-item>
      <px-button type="primary" @click="queryTable">查询</px-button>
      <px-button @click="resetTable">重置</px-button>
    </px-form>
    <div class="equip-table-btn">
      <px-button v-has="'MACHINE_REPORT_PO_IMPORT'" type="primary" plain @click="showImportDialog">导入</px-button>
    </div>
    <px-table :data="tableData" class="equip-table" height="calc(100vh - 380px)" border>
      <template #empty>
        <px-empty />
      </template>
      <px-table-column prop="recordNumber" label="单据编号" min-width="80" />
      <px-table-column prop="poNumber" label="PO号" min-width="100" />
      <px-table-column prop="poType" label="PO类型" min-width="100" />
      <px-table-column prop="projectName" label="工程名称" min-width="100" />
      <px-table-column prop="boQName" label="BOQ名称" min-width="100" />
      <px-table-column prop="topicPrice" label="合计" min-width="100" />
      <px-table-column prop="createTime" label="单据创建时间" min-width="100" />
      <px-table-column prop="creator" label="单据创建人" min-width="100" />
      <px-table-column prop="fileDTOList" label="BOQ附件下载" min-width="100">
        <template #default="scope">
          <div v-if="scope.row.fileDTOList">
            <px-link v-for="item in scope.row.fileDTOList" :key="item.id" type="primary" target="_blank" :href="item.fileDTO.fileUrl">{{
              item.fileDTO.originalName
            }}</px-link>
          </div>
        </template>
      </px-table-column>
      <px-table-column label="操作" align="center" width="120" class-name="small-padding fixed-width">
        <template #default="scope">
          <px-tooltip content="详情" placement="top">
            <px-button v-has="'MACHINE_REPORT_PO_VIEWDETAIL'" link type="primary" icon="Tickets" @click="handleDetail(scope.row)" />
          </px-tooltip>
          <px-tooltip content="修改" placement="top">
            <px-button v-has="'MACHINE_REPORT_PO_EDIT'" link type="primary" icon="Edit" @click="handleUpdate(scope.row)" />
          </px-tooltip>
          <px-tooltip content="删除" placement="top">
            <px-button v-has="'MACHINE_REPORT_PO_DELETE'" link type="danger" icon="Delete" @click="handleDelete(scope.row)" />
          </px-tooltip>
        </template>
      </px-table-column>
    </px-table>
    <pagination
      v-show="total > 0"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      class="equip-table-pagination"
      :total="total"
      @pagination="queryTable"
    />
    <!-- 导入 -->
    <div v-if="fileUploadVisible">
      <FileUpload v-model:visible="fileUploadVisible" :type="type" limit="1" :poRecordId="poRecordId" @uploadAction="fileUploadConfirm" />
    </div>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "MACHINE_REPORT_CHECK"
});
import { queryChildByTypeCodeAndItemValue } from "@/api/handover";
import { importReport, querySelectCondition, queryPoRecord, queryPoDetail, deletePoRecord, updateImportReport } from "@/api/machineReport";
import { formatDuration } from "@/utils/pengxi";
import { PxMessage, PxMessageBox } from "px-ui";
import { onMounted, reactive, toRefs, ref } from "vue";
import FileUpload from "./components/fileUpload.vue";
import { getToken } from "@/utils/auth";
import { useRouter } from "vue-router";
import { useRouterStoreHook } from "@/store/modules/router";
import dayjs from "dayjs";

const routerStore = useRouterStoreHook();

onMounted(() => {
  getSelectList();
  queryTable();
  // querySelectList();
});

const defaultProps = {
  children: "children",
  label: "name",
  value: "code"
};
const state = reactive<Record<string, any>>({
  queryParams: {
    pageNum: 1,
    pageSize: 20
  },
  tableData: [], // 列表数据
  total: 0, // 列表数量
  rowData: {}, //
  dialogVisible: false, // 弹窗显示隐藏
  dialogType: "add", // 弹窗默认新增
  poTypeList: [
    {
      label: "计划PO",
      value: "计划PO"
    },
    {
      label: "OPEN PARTS",
      value: "OPENPARTS"
    }
  ],
  poNoList: [],
  poCreatorList: [],
  fileUploadVisible: false,
  type: "add",
  poRecordId: ""
});

const {
  queryParams,
  tableData,
  total,
  rowData,
  dialogVisible,
  dialogType,
  poTypeList,
  poNoList,
  poCreatorList,
  fileUploadVisible,
  type,
  poRecordId
} = toRefs(state);

const showImportDialog = () => {
  type.value = "add";
  fileUploadVisible.value = true;
  poRecordId.value = "";
};

const fileUploadConfirm = async data => {
  let fileList = data.fileList;
  let formData = new FormData();
  if (type.value == "edit") {
    formData.append("poRecordId", poRecordId.value);
    formData.append("file", fileList[0].raw);
    await updateImportReport(formData);
    fileUploadVisible.value = false;
    PxMessage.success("上传成功");
    queryTable();
  } else {
    formData.append("poType", data.poType);
    formData.append("poNumber", data.poNo);
    formData.append("file", fileList[0].raw);
    await importReport(formData);
    fileUploadVisible.value = false;
    PxMessage.success("上传成功");
    queryTable();
  }
};

// 搜索查询条件下拉框
const getSelectList = async () => {
  let res = await querySelectCondition();
  poNoList.value = res.PoNumber || [];
  // poTypeList.value = res.PoPoType || [];
  poCreatorList.value = res.PoCreator || [];
};

const handleDetail = row => {
  poRecordId.value = row.id;
  type.value = "preview";
  fileUploadVisible.value = true;
};
const handleUpdate = row => {
  poRecordId.value = row.id;
  type.value = "edit";
  fileUploadVisible.value = true;
};
const handleDelete = row => {
  PxMessageBox.confirm(`删除后不可恢复，继续删除吗？`, "提示", {
    confirmButtonText: "删除",
    confirmButtonClass: "px-button--danger",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      await deletePoRecord({ poRecordIdList: [row.id] });
      PxMessage.success("删除成功");
      queryTable();
    })
    .catch(() => {});
};
const queryTable = async () => {
  const temp = JSON.parse(JSON.stringify(queryParams.value));
  temp.recordDateStart = queryParams.value?.createTime?.[0];
  temp.recordDateEnd = queryParams.value?.createTime?.[1];
  const res = await queryPoRecord({ ...temp });
  tableData.value = res.data || [];
  // tableData.value.forEach(v => {
  //   if (v.fileInfo) {
  //     v.fileInfo = JSON.parse(v.fileInfo);
  //   }
  // });
  // total.value = res?.total;
};
// // 重置筛选条件和运行记录列表
const resetTable = async () => {
  queryParams.value = {
    annual: new Date().getFullYear(),
    pageNum: 1,
    pageSize: 20
  };
  queryTable();
};
</script>

<style lang="scss" scoped>
@import url("@/views/all/equip/scss/table-list.scss");

.equip-wrap-common {
  height: calc(100vh - 177px);

  .summary {
    display: flex;
    width: 43%;
    padding: 16px 0;

    .s-item {
      flex: 1;

      span {
        font-weight: bold;
        color: #3b82f6;
      }
    }
  }

  .equip-form {
    margin-bottom: 8px;

    :deep(.px-form-item) {
      width: 20%;
      margin-bottom: 8px;
    }

    :deep(.px-button) {
      margin-top: -8px;
    }
  }
}
</style>
